package com.dems.remote.ali;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.Protocol;
import com.dems.core.util.DateUtil;
import com.dems.domain.upload.FileUploadDto;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Component
@RefreshScope
public class OssUtil {

    // LTAI5tJpaqDRrSrC2jtUnJgB
    // GsWJU8yg62gkdSH7mlwPPfKlbv7X3j
    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    public static final String endpoint = "oss-cn-shanghai.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    public static final String accessKeyId = "LTAI5tJpaqDRrSrC2jtUnJgB";
    public static final String accessKeySecret = "GsWJU8yg62gkdSH7mlwPPfKlbv7X3j";
    public static final String BUCKET_DOMAIN = "loan-assist.oss-cn-shanghai.aliyuncs.com";
    public static final String BUCKET_NAME = "loan-assist";

    @Value("${ali.sms.accessKeyId}")
    private String ACCESS_KEY_ID;

    @Value("${ali.sms.accessKeySecret}")
    private String ACCESS_KEY_SECRET;

    public static final String BUCKET_DOMAIN_SIP = "sip-audio.oss-cn-shanghai.aliyuncs.com";
    public static final String BUCKET_NAME_SIP = "sip-audio";


    public String uploadFile(FileUploadDto fileUploadDto) {

        ClientBuilderConfiguration clientConfiguration = new ClientBuilderConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTPS);

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET, clientConfiguration);

        String key = DateUtil.getCurrentYearMonth() + "/" + UUID.randomUUID() + "_" + fileUploadDto.getFileName();
        if(fileUploadDto.getOssKey() != null){
            key = fileUploadDto.getOssKey();
        }
        // 填写Byte数组。
        byte[] content = Base64Utils.decodeFromString(fileUploadDto.getBase64Content());
        // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(BUCKET_NAME_SIP, key, new ByteArrayInputStream(content));

        URL url = ossClient.generatePresignedUrl(BUCKET_NAME_SIP, key, DateUtils.addYears(new Date(), 10));

        // 关闭OSSClient。
        ossClient.shutdown();

        return url.toString();
    }

    public String fetchUrl(String ossKey) {

        ClientBuilderConfiguration clientConfiguration = new ClientBuilderConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTPS);

        OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET, clientConfiguration);

        URL url = ossClient.generatePresignedUrl(BUCKET_NAME_SIP, ossKey, DateUtils.addYears(new Date(), 1));

        ossClient.shutdown();

        return url.toString();
    }

    public void uploadKpiNSFile(ByteArrayOutputStream out, String key) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        byte[] content = out.toByteArray();

        ossClient.putObject(BUCKET_NAME_SIP, key, new ByteArrayInputStream(content));

        URL url = ossClient.generatePresignedUrl(BUCKET_NAME_SIP, key, DateUtils.addYears(new Date(), 1));

        ossClient.shutdown();
    }
}
